package com.seari.groovyrunner.controller;


import com.seari.groovyrunner.bean.DataGridBean;
import com.seari.groovyrunner.bean.GroovyTask;
import com.seari.groovyrunner.config.Constants;
import com.seari.groovyrunner.main.StartUpClass;
import com.seari.groovyrunner.service.GroovyService;
import com.seari.groovyrunner.utils.FileUtil;
import com.seari.groovyrunner.utils.GrooyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping(value = "groovy")
public class GroovyController {

    @Value("${groovy.batpath}")
    private String PATH ;

    @Value("${groovy.visit.ip}")
    private String visitIP ;

    @Autowired
    public GroovyService groovyService;

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    @ResponseBody
    public DataGridBean<GroovyTask> search(@RequestParam(value = "taskName")String taskName,@RequestParam(value = "page")String page,@RequestParam(value = "limit")String limit){
        DataGridBean<GroovyTask> dataDataGridBean = new DataGridBean<>();
        List<GroovyTask> baseTask = groovyService.getTaskListByName(taskName,page,limit);
        int count = groovyService.getTaskListCountByName(taskName);
        for (GroovyTask groovy : baseTask) {
            groovy.setGurl(groovy.getGservice());
            groovy.setGservice(visitIP+ Constants.baseUrl+groovy.getGservice());
        }
        dataDataGridBean.setMsg("success");
        dataDataGridBean.setTotal(count);
        dataDataGridBean.setRows(baseTask);
        dataDataGridBean.setCode(200+"");
        return dataDataGridBean;
    }
    @RequestMapping(value = "/searchScript",method = RequestMethod.GET)
    @ResponseBody
    public DataGridBean<GroovyTask> searchScript(@RequestParam(value = "taskName")String taskName,@RequestParam(value = "page")String page,@RequestParam(value = "limit")String limit){
        DataGridBean<GroovyTask> dataDataGridBean = new DataGridBean<>();
        List<GroovyTask> baseTask =new ArrayList<>();
        int startIndex = (Integer.valueOf(page) - 1) * Integer.valueOf(limit);
        int end= startIndex+Integer.valueOf(limit);
        File file=new File(PATH);
        File[] files = file.listFiles();
        int count;
        if (taskName==null||taskName.equals("")){
            end=end>files.length?files.length:end;
            for (int i = startIndex; i < end; i++) {
                GroovyTask bean=new GroovyTask();
                bean.setGid(i);
                bean.setGname(files[i].getName());
                bean.setGpath(files[i].getAbsolutePath());
                baseTask.add(bean);
            }
            count=files.length;
        }else{
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().contains(taskName)){
                    GroovyTask bean=new GroovyTask();
                    bean.setGid(i);
                    bean.setGname(files[i].getName());
                    bean.setGpath(files[i].getAbsolutePath());
                    baseTask.add(bean);
                }
            }
            count=baseTask.size();
            startIndex=startIndex>baseTask.size()?baseTask.size():startIndex;
            end=end>baseTask.size()?baseTask.size():end;
            baseTask = baseTask.subList(startIndex, end);
        }
        dataDataGridBean.setMsg("success");
        dataDataGridBean.setRows(baseTask);
        dataDataGridBean.setTotal(count);
        dataDataGridBean.setCode(200+"");
        return dataDataGridBean;
    }
    @RequestMapping(value = "/fileList",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getGroovyFileList(){
        Map<String, Object> result = new HashMap<>();
        List<GroovyTask> baseTask =new ArrayList<>();
        File file=new File(PATH);
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            GroovyTask bean=new GroovyTask();
            bean.setGid(i);
            bean.setGname(files[i].getName());
            bean.setGpath(files[i].getAbsolutePath());
            baseTask.add(bean);
        }
        result.put("data", baseTask);
        result.put("count", baseTask.size());
        result.put("code", 200);
        result.put("msg", "");
        return result;
    }

    @RequestMapping(value = "/addScript",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addScript(@RequestParam(value = "code")String code,@RequestParam(value = "name")String name){
        Map<String, Object> result = new HashMap<>();
        try {
            String s = GrooyUtils.checkGroovyScript(code);
            if (!s.equals("success")){
                result.put("code",500);
                result.put("msg",s);
                return result;
            }
            if (FileUtil.saveFile(PATH+name,code)){
                result.put("code",200);
                result.put("msg","success");
            }else {
                result.put("code", 500);
                result.put("msg", "文件已存在");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "系统异常");
        }
        return result;
    }
    @RequestMapping(value = "/editScript",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editScript(@RequestParam(value = "code")String code,@RequestParam(value = "name")String name,@RequestParam(value = "cname")String cname){
        Map<String, Object> result = new HashMap<>();
        try {
            String s = GrooyUtils.checkGroovyScript(code);
            if (!s.equals("success")){
                result.put("code",500);
                result.put("msg",s);
                return result;
            }
            File file = new File(PATH+name);
            if (cname.equals(name)){
                FileWriter writer=new FileWriter(file,false);
                writer.write(code);
                writer.close();
                result.put("code",200);
                result.put("msg","success");
            }else{
                if (file.exists()){
                    result.put("code", 500);
                    result.put("msg", "文件名已存在");
                }else{
                    new File(PATH+cname).delete();
                    FileWriter writer=new FileWriter(file,false);
                    writer.write(code);
                    writer.close();
                    result.put("code",200);
                    result.put("msg","success");
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "系统异常");
        }
        return result;
    }
    @RequestMapping(value = "/getScript",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getScript(@RequestParam(value = "name")String name,@RequestParam(value = "path")String path){
        Map<String, Object> result = new HashMap<>();
        try {
            File file = new File(path);
            if (file.exists()){
                String code = FileUtil.readFile(file);
                result.put("data",code);
                result.put("code",200);
                result.put("msg","success");
            }else {
                result.put("code", 500);
                result.put("msg", "文件不存在");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "系统异常");
        }
        return result;
    }
    @RequestMapping(value = "/getMethod",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getMethod(@RequestParam(value = "name")String name,@RequestParam(value = "path")String path){
        Map<String, Object> result = new HashMap<>();
        try {
            List<String> groovyMethod = GrooyUtils.getGroovyMethod(path);
            result.put("data",groovyMethod);
            result.put("code",200);
            result.put("msg","success");
        }catch (Exception e){
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", e.getMessage());
        }
        return result;
    }
    @RequestMapping(value = "/addService",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addService(@RequestParam(value = "name")String name,@RequestParam(value = "path")String path,@RequestParam(value = "method")String method,@RequestParam(value = "describe")String describe,@RequestParam(value = "service")String service){
        Map<String, Object> result = new HashMap<>();
        try {
            List<GroovyTask> taskListByService = groovyService.getTaskListByService(service);
            if (taskListByService.size()==0){
                GroovyTask task=new GroovyTask();
                task.setGname(name);
                task.setGmethod(method);
                task.setGpath(path);
                task.setGdescribe(describe);
                task.setGservice(service);
                task.setGstate(1);
                groovyService.addService(task);
                result.put("msg", "success");
                result.put("code", 200);
            }else{
                result.put("msg", "已存在相同访问路径任务");
                result.put("code", 500);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping(value = "/updateService",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateService(@RequestParam(value = "id")Integer id,@RequestParam(value = "name")String name,@RequestParam(value = "path")String path,@RequestParam(value = "method")String method,@RequestParam(value = "describe")String describe,@RequestParam(value = "service")String service){
        Map<String, Object> result = new HashMap<>();
        try {
            GroovyTask oldTask=groovyService.getTaskByID(id);
            if (oldTask.getGservice().equals(service)){
                oldTask.setGname(name);
                oldTask.setGmethod(method);
                oldTask.setGpath(path);
                oldTask.setGdescribe(describe);
                groovyService.updateService(oldTask);
                result.put("msg", "success");
                result.put("code", 200);
            }else{
                List<GroovyTask> taskListByService = groovyService.getTaskListByService(service);
                if (taskListByService.size()<1){
                    oldTask.setGname(name);
                    oldTask.setGmethod(method);
                    oldTask.setGpath(path);
                    oldTask.setGdescribe(describe);
                    oldTask.setGservice(service);
                    groovyService.updateService(oldTask);
                    if (oldTask.getGstate()==0){
                        StartUpClass.serviceMapping.remove(oldTask.getGservice());
                        StartUpClass.serviceMapping.put(service,oldTask);
                    }
                    result.put("msg", "success");
                    result.put("code", 200);
                }else{
                    result.put("msg", "已存在相同访问路径任务");
                    result.put("code", 500);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping(value = "/scriptState",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> scriptState(@RequestParam(value = "id")Integer id,@RequestParam(value = "state")String state,@RequestParam(value = "path")String path,@RequestParam(value = "method")String method,@RequestParam(value = "service")String service){
        Map<String, Object> result = new HashMap<>();
        try {
            GroovyTask groovyTask = StartUpClass.serviceMapping.get(service);
            if (state.equals("start")&&groovyTask==null){
                groovyTask=new GroovyTask();
                groovyTask.setGpath(path);
                groovyTask.setGmethod(method);
                groovyTask.setGid(id);
                groovyTask.setGservice(service);
                groovyService.changeScriptStateById(0,id);
                StartUpClass.serviceMapping.put(service,groovyTask);
                result.put("code","200");
                result.put("msg","success");
            }else if (state.equals("start")){
                result.put("code","500");
                result.put("msg","已启动脚本无法重复启动");
            }else if (groovyTask==null){
                result.put("code","500");
                result.put("msg","已关闭脚本无法重复关闭");
            }else{
                groovyService.changeScriptStateById(1,id);
                StartUpClass.serviceMapping.remove(service);
                result.put("code","200");
                result.put("msg","success");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    @RequestMapping(value = "/deleteService",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteService(@RequestParam(value = "id")Integer id){
        Map<String, Object> result = new HashMap<>();
        try {
            GroovyTask taskByID = groovyService.getTaskByID(id);
            if (taskByID.getGstate()==0){
                result.put("code", 500);
                result.put("msg", "请先暂停脚本服务");
            }else {
                groovyService.deleteTaskByID(id);
                result.put("code",200);
                result.put("msg","删除成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "系统异常");
        }
        return result;
    }
    @RequestMapping(value = "/deleteScript",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteScript(@RequestParam(value = "path")String path){
        Map<String, Object> result = new HashMap<>();
        try {
            String substring = path.substring(path.lastIndexOf("\\")+1);
            List<GroovyTask> list=groovyService.getTaskListByPath(substring);
            if (list.size()>0){
                result.put("code", 500);
                result.put("msg", "脚本文件正在使用中");
            }else{
                File file = new File(path);
                if (file.exists()){
                    file.delete();
                    result.put("code",200);
                    result.put("msg","删除成功");
                }else {
                    result.put("code", 500);
                    result.put("msg", "文件不存在");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "系统异常");
        }
        return result;
    }
}
